#include "headfile.h"

volatile float AD_V_power,AD_I_power,AD_CapV_power;
volatile float Control_Integral=0,Control_Out=0;
volatile float Now_Power=0,Target_Power=15;
volatile float Max_Cap_Voltage = 10;
volatile float Power_p=20,Power_i=1;
uint8 Flag_power=0;

void charge_adc_read(void){	
	float AD_I[10],AD_V[10],AD_CapV[10];
	int i;
	AD_V_power=0;
	AD_I_power=0;
	AD_CapV_power=0;
	
	for(i=0;i<10;i++){
		AD_I[i]=adc_once(PIN_CHARGE_I,ADC_12BIT);
		AD_V[i]=adc_once(PIN_CHARGE_V,ADC_12BIT);
		AD_CapV[i]=adc_once(PIN_CHARGE_CAP,ADC_12BIT);
	}
	for(i=0;i<10;i++){
		AD_I_power+=AD_I[i];
	  	AD_V_power+=AD_V[i];
		AD_CapV_power+=AD_CapV[i];
	}
	AD_I_power=AD_I_power/10;
	AD_V_power=AD_V_power/10;
	AD_CapV_power=AD_CapV_power/10;

	AD_V_power=(AD_V_power/4096)*5*11;
	AD_CapV_power=(AD_CapV_power/4096)*5*11;
	AD_I_power=(AD_I_power/4096)*5/20/0.02;		//mA
}

void charge_power_control(){
	float fP,fI,fDelta=0;

	Now_Power=(AD_V_power)*(AD_I_power);
	fDelta=Target_Power-Now_Power;
	fP=fDelta*Power_p;
	fI=fDelta*Power_i;

	Control_Integral+=fI;   
	if(Control_Integral>2000)Control_Integral=2000;
	
	Control_Out=fP+Control_Integral;
	if(Control_Out>4000)Control_Out=4000;
	
// Control_Out =  1150;
Control_Out = (3500 - AD_CapV_power*250);
	// Control_Out =  2000;

	if(AD_CapV_power>Max_Cap_Voltage){
		Control_Out=0;
		Flag_power=1;
	}




	pwm_duty(PIN_CHARGE_PWM,(uint16)Control_Out);       //占空比比例不同

}

void charge_init(void){
	adc_init(PIN_CHARGE_V,ADC_SYSclk_DIV_16);
	adc_init(PIN_CHARGE_I,ADC_SYSclk_DIV_16);
	adc_init(PIN_CHARGE_CAP,ADC_SYSclk_DIV_16);	
	pwm_init(PIN_CHARGE_PWM,10000, 0);
}

void charge_exe(void){
	charge_adc_read();
	if(Flag_power==0){   
		charge_power_control();
	}
}
		
void charge_parameter(float p,float i,float t){
	Power_p = p;
	Power_i = i;
	Target_Power=t;
}

void charge_lcd_msg(void){

	lcd_clear(WHITE);
	lcd_showstr(0,0,"U:");lcd_showstr(0,1,"V:");lcd_showstr(0,2,"I:");lcd_showstr(0,3,"P:");
	lcd_showstr(0,4,"D:");lcd_showstr(0,5,"p:");lcd_showstr(0,6,"i:");lcd_showstr(0,7,"T:"); 

	lcd_showfloat(20,0,AD_CapV_power,6,6);               				
	lcd_showfloat(20,1,AD_V_power,6,6);               				
	lcd_showfloat(20,2,AD_I_power,6,6);
	lcd_showfloat(20,3,Now_Power,6,6);
	lcd_showfloat(20,4,Control_Out*100/10000,6,6);
	lcd_showfloat(20,5,Power_p,6,6);
	lcd_showfloat(20,6,Power_i,6,6);
	lcd_showfloat(20,7,Target_Power,6,6);
}

void charge_show(void){
	uprintf("U:%.6f\r\n",AD_CapV_power);               				
	uprintf("V:%.6f\r\n",AD_V_power);               		
	uprintf("I:%.6f\r\n",AD_I_power);
	uprintf("NOW_POWER%.6f\r\n",Now_Power);
	uprintf("PWM_OUT:%.6f\r\n",Control_Out*100/10000);
	uprintf("kp:%.6f\r\n",Power_p);
	uprintf("ki:%.6f\r\n",Power_i);
	uprintf("TARGET_POWER:%.6f\r\n",Target_Power);
}
